(function ($) {
  var total_number = 0, editing = false, curOffset = 0;

  $(document).on('ready', function () {
    service.init();
    bindEvents();
    getFavors();
  })

  function bindEvents() {
    $('#edit').on('click', function () {
      this.textContent = isEditing() ? "编辑" : "完成";
      toggleEditing();
    });

    $('#novel_list').on('click', '.radio_btn', function () {
      var self = $(this);
      var item = self.closest('tr');

      service.unFavor(item.get(0).id, function () {
        onUnFavorSuccess(item);
      }, function () {

      });
    });

    $('#novel_list').on('click', 'tr', function () {
      if (isEditing()) return false;
      location.href = 'detail.html?id=' + encodeURIComponent($(this).data('id'));
    })

    $('#search_btn').on('click', function () {
      location.href = 'search.html';
    })

    $('.list_more').on('click', function () {
      getFavors();
    })
  }

  function onUnFavorSuccess(item) {
    item.remove();
    total_number--;
    if(total_number <= 0) {
      total_number = 0;
      disableEditing();
      hideEditBtn();
      showEmptyPage();
    }
    $("#total_number").text(total_number);
  }

  function updateFavorElems(favors) {
    if(favors.length == 0) {
      if(!curOffset) showEmptyPage();
      return;
    }
    curOffset += favors.length;
    if (total_number <= curOffset) {
      $('.list_more').hide();
    }
    showEditBtn();
    var favorElems = [];
    for(var i = 0; i < favors.length; i++) {
      var favorElem = makeFavorElem(favors[i]);
      if(!favorElem) continue;
      favorElems.push(favorElem);
    }
    $("#novel_list > tbody").append(favorElems);
  }

  function onNetError() {
    if (!curOffset) hideEditBtn();
  }

  function showEmptyPage() {
    $("#empty").show();
  }

  function showEditBtn () {
    $('#edit').show();
  }

  function hideEditBtn () {
    $('#edit').hide();
  }

  function isEditing() {
    return $("#novel_list").hasClass("editing");
  }

  function toggleEditing() {
    $("#novel_list").toggleClass("editing");
  }

  function disableEditing() {
    $("#novel_list").removeClass('editing');
  }

  function makeFavorElem(favor) {
    if (!favor.favor_id || !favor.novel_name) return;

    var item = '<tr>' +
        '<td class="control_area"><div class="radio_btn"></div></td>' +
        '<td class="novel_info">' +
        '<div class="novel_name ellipsis"></div>' +
        '<div class="baidu_index ellipsis"></div>' +
        '<div class="baidu_suffix"><span>最近</span></div></td>' +
        '<td style="position:relative"> <div class="chart"></div><div class="chart_suffix">30天</div></td>' +
        '</tr>';
    var tr = $(item), value = undefined, date = '';
    if (favor.baidu_indices && favor.baidu_indices.length > 0) {
      var last = favor.baidu_indices.length - 1;
      value = util.shortNumber(favor.baidu_indices[last].value);
    }
    tr.attr('id', favor.favor_id)
        .attr('data-id', favor.novel_id)
        .find('.novel_name').text(favor.novel_name);
    if(value === undefined) {
      tr.find('.baidu_index').html('<img src="imgs/no_data.png"/>');
    } else {
      tr.find('.baidu_index').text(value);
      tr.find('.baidu_suffix').css('display', 'block');
      tr.find('.chart_suffix').css('display', 'block');
    }
    createChart(favor.baidu_indices, tr);
    return tr;
  }

  function createChart(indices, elem) {
    if (!indices) {
      elem.find('.chart').addClass('no-data');
      return;
    }

    var dates = [], values = [], minValue, maxValue;
    minValue = maxValue = indices[0].value;
    for(var i = 0; i < indices.length; ++i) {
      dates.push(indices[i].date);
      values.push(indices[i].value);
      minValue = Math.min(minValue, indices[i].value);
      maxValue = Math.max(maxValue, indices[i].value);
    }
    maxValue *= 1.2;
    minValue *= 0.9;
    var option = {
      backgroundColor: '#fff',
      tooltip: {},
      grid: {
        left: '3%',
        top: '7%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        axisTick: {
          show: false
        },
        axisLine: {
          show: false
        },
        axisLabel: {
          show: false
        },
        data: dates
      },
      yAxis: {
        type: 'value',
        min: minValue,
        max: maxValue,
        splitLine: {
          show: false
        },
        axisTick: {
          show: false
        },
        axisLine: {
          show: false
        },
        axisLabel: {
          show: false
        }
      },
      series: [{
        name: 'index',
        type: 'line',
        itemStyle: {
          normal: {
            color: '#89bbff'
          }
        },
        lineStyle: {
          normal: {
            width: 4
          }
        },
        data: values
      }]
    };
    setTimeout(function () {
      var chart = echarts.init(elem.find('.chart').get(0));
      chart.setOption(option);
    },0);
  }

  function getFavors () {
    service.getFavorList(function (data) {
      total_number = data.total_number;
      $("#total_number").text(total_number);
      updateFavorElems(data.favors);
    }, function () {
      onNetError();
    }, curOffset);
  }

})(Zepto);
